let fs = require("fs");
let colors = require("colors");
let stdin = process.stdin;
let stdout = process.stdout;



colors.setTheme({
  silly: 'rainbow',
  input: 'grey',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

fs.readdir(process.cwd(),function(error,files){


    if( error ){
        console.log("Get files failed.".error)
    }
    if( files.length === 0 ){
        console.log('no files to show!'.warn)
    }
    console.log('Select which file or directory you want to see.\n'.input);


    function read(){
        stdout.write('Enter your choice:  '.debug);
        stdin.resume();
        stdin.setEncoding("utf8");
        stdin.on("data",option)
    }
    
    function option(data){
        let filename = files[Number(data)];
        if( !filename ){
            stdout.write("Enter your chioce: ".debug)
        }else{
            if( stats[Number(data)].isDirectory() ){
                fs.readdir(__dirname+"/"+filename,function(error,files){
                    if( error ){
                        console.log("Get files failed.".error)
                    }
                    if( files.length === 0 ){
                        console.log('no files to show!'.warn)
                    }
                    files.forEach(function(file){
                        console.log( `----${file}`.info )
                    })
                    stdin.pause();
                })
            }else{
                stdout.write(`You choosed filename: ${filename}\n`)
                stdin.pause();
                fs.readFile(__dirname+'/'+filename,'utf8',function(error,data){
                    if( error ){
                        console.log("File read failed".error)
                    }
                    console.log(data.warn)
                })
            }
        }
    }


    let stats = [];
    function file(i){
        var filename = files[i];
        fs.stat(__dirname+"/"+filename,function(error,stat){
            stats[i] = stat;
            if( stat.isDirectory() ){
                console.log(`${i}:${filename}`.prompt)
            }else{
                console.log(`${i}:${filename}`.info)
            }
            i++;
            if( i === files.length ){
                read()
            }else{
                file(i)
            }

        })
    }
    file(0)
})